//
//  EFANotSelModeVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/9/1.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFANotSelModeVC.h"
#import <MJRefresh.h>
#import <UIScrollView+EmptyDataSet.h>
#import "ApiManager.h"
#import "EFAPjtSelPjtTCell.h"
#import "EFAModel.h"
#import "UIColor+XDHex.h"
#import "GlobalHeader.h"
#import "EFANotSelPjtVC.h"

@interface EFANotSelModeVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>
@property (weak,   nonatomic) IBOutlet UITableView *tableView;
//@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
//@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;
@property (strong, nonatomic) UIBarButtonItem *sureBarBtnItem;
@property (strong, nonatomic) UIBarButtonItem *cancelBarBtnItem;
@property (strong, nonatomic) NSArray<NSString *> *titleArray;
@end

static NSString *const kReuseCellId = @"EFAPjtSelPjtTCell";
//static NSInteger const kRequestSize = 20;

@implementation EFANotSelModeVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

//- (BOOL)hidesBottomBarWhenPushed {
//    return self.viewType == EFAPjtManagerVCTypeManager;
//}

- (void)initNavigationBar {
    self.navigationItem.title = @"谁可以看";
    self.navigationItem.leftBarButtonItem = self.cancelBarBtnItem;
    self.navigationItem.rightBarButtonItem = self.sureBarBtnItem;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)initSubViews {
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
//    self.tableView.emptyDataSetDelegate = self;
//    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
//    self.tableView.mj_header = self.mj_header;
    //    self.tableView.mj_footer = self.mj_footer;
    
//    [self.tableView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"当前没有项目" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    //    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
    return nil;
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return 1;
//}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.titleArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EFAPjtSelPjtTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.row < self.titleArray.count) {
        cell.titleLabel.text = self.titleArray[indexPath.row];
    }
    cell.selBtn.selected = (self.defaultMode == indexPath.row + 1);
    if (indexPath.row > 0 && self.defaultMode == (indexPath.row + 1)) {
        cell.subTitleLabel.text = [NSString stringWithFormat:@"已选%ld个项目", (unsigned long)self.selPjtArray.count];
    } else {
        cell.subTitleLabel.text = nil;
    }
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 14.9;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row == 0) {
        self.defaultMode = indexPath.row + 1;
        self.selPjtArray = nil;
        [self refreshWholeView];
    } else {
        [self jumpToSelectPjtWithIndexPath:indexPath];
    }
}

#pragma mark - event response
- (void)cancelBarBtnTapped:(UIBarButtonItem *)item {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)sureBarBtnTapped:(UIBarButtonItem *)item {
    if (self.successHandle) {
        self.successHandle(self.defaultMode, self.selPjtArray);
        self.successHandle = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - private methods
- (void)jumpToSelectPjtWithIndexPath:(NSIndexPath *)indexPath {
    EFANotSelPjtVC *vc = [[EFANotSelPjtVC alloc] init];
    vc.successHandle = ^(NSArray<EFAPjtListItem *> *selArray) {
        if (selArray.count) {
            self.defaultMode = indexPath.row + 1;
            self.selPjtArray = selArray;
            [self refreshWholeView];
        }
    };
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)refreshWholeView {
//    // 尾部加载更多的显示
//    if (self.pjtModel.totalLoad) {
//        [self.tableView.mj_footer endRefreshingWithNoMoreData];
//    } else {
//        [self.tableView.mj_footer resetNoMoreData];
//    }
    
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
//    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
//    [self requestPjtListWithHeader:isHeader];
}

//- (EFAProjectModel *)deviceModelWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)AddMore {
//    if ([dic[EFAGlobalJsonKeyErrCode] integerValue] != 200) {
//        return self.pjtModel;
//    }
//
//    EFAProjectModel *temp = [EFAProjectModel yy_modelWithDictionary:dic[EFAGlobalJsonKeyResult]];
//    if (!temp) {
//        return self.pjtModel;
//    }
//
//    if (AddMore && self.pjtModel) {
//        [self.pjtModel addMoreWithData:temp];
//    } else {
//        self.pjtModel = temp;
//    }
//    return self.pjtModel;
//}

#pragma mark - network request
//- (void)requestPjtListWithHeader:(BOOL)isHeader {
//    // 发布Cos需要登录
//    if (![EFAModel sharedInstance].isLogin) {
//        [self tableViewEndRefresh:isHeader];
//        return;
//    }
//    
//    //    NSInteger startIndex = isHeader ? 0 : self.userList.user_list.count;
//    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
//                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token};
//    
//    [[XDAFNetworking sharedInstance] GET:[ApiManager apiProjectList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"请求项目列表返回：%@", responseObject);
//        [self tableViewEndRefresh:isHeader];
//        self.pjtModel = [EFAProjectModel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
//        [self refreshWholeView];
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"请求项目列表失败：%@", error);
//        [self tableViewEndRefresh:isHeader];
//        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
//        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
//    }];
//}

#pragma mark - getters and setters
- (UIBarButtonItem *)cancelBarBtnItem {
    if (!_cancelBarBtnItem) {
        _cancelBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelBarBtnTapped:)];
        //        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
        //                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        //        [_cancelBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
        //        NSDictionary * disableBarItemAtt = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen alpha:0.5],
        //                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        //        [_cancelBarBtnItem setTitleTextAttributes:disableBarItemAtt forState:UIControlStateDisabled];
    }
    return _cancelBarBtnItem;
}
- (UIBarButtonItem *)sureBarBtnItem {
    if (!_sureBarBtnItem) {
        _sureBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(sureBarBtnTapped:)];
        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_sureBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
        NSDictionary * disableBarItemAtt = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen alpha:0.5],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_sureBarBtnItem setTitleTextAttributes:disableBarItemAtt forState:UIControlStateDisabled];
    }
    return _sureBarBtnItem;
}
//- (MJRefreshNormalHeader *)mj_header {
//    if (!_mj_header) {
//        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
//        _mj_header.lastUpdatedTimeLabel.hidden = YES;
//    }
//    return _mj_header;
//}
//
//- (MJRefreshAutoNormalFooter *)mj_footer {
//    if (!_mj_footer) {
//        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
//        _mj_footer.automaticallyRefresh = NO;
//        _mj_footer.automaticallyHidden = YES;
//    }
//    return _mj_footer;
//}

- (NSArray<NSString *> *)titleArray {
    if (!_titleArray) {
        _titleArray = @[@"所有项目可见", @"部分项目可见", @"部分项目不可见"];
    }
    return _titleArray;
}
@end
